<?php

namespace app\admin\controller\mall\goods;

use app\common\controller\Backend;

/**
 * 销售规格
 *
 * @icon fa fa-circle-o
 */
class Salespec extends Backend
{
    /**
     * Salespec模型对象
     * @var \app\common\model\mall\goods\Salespec
     */
    protected $model = null;
    protected $multiFields = 'defaultis';

    protected $goods_id = null;
    protected $Items = null;//已设置规格项数据
    protected $buildSaleSpecIs = true;//已生成销售规格

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\mall\goods\Salespec;
        $this->goods_id = $this->request->param('goods_id');
        $this->assignconfig('goods_id', $this->goods_id);
        //$this->assign("goods_id", $this->goods_id);
        //获取规格项
        $this->Items = collection(\app\common\model\mall\goods\Specitem::where("goods_id",$this->goods_id)
            ->field("itemId,spec_id,itemname,itemimg")
            ->order("spec_id,itemId")->select())->toArray();
        if(empty($this->Items)) $this->error("未设置任何规格项，无法生成销售规格！");

        $this->assignconfig('buildSaleSpecIs', $this->buildSaleSpecIs);

        //获取已设置的分类规格ID
        $specids = array_column($this->Items,"spec_id");
        $specids = array_unique($specids);
        //获取商品的分类IDS
        $cat_ids = $this->request->param('cat_ids');
        $this->assignconfig('cat_ids', $cat_ids);
        $specs = db('mall_goods_catspec')
            ->where(["cat_id"=>["in", $cat_ids],"showis"=>1,"id"=>["in", $specids]])
            ->column("specname,allowimgis,id","id");
        //渲染到js，以便生成已设置的规格列
        $this->assignconfig('specs', $specs);

    }

    /**
     * 查看
     */
    public function index()
    {
        $total = $this->model
            ->where("goods_id",$this->goods_id)
            ->count();
        if($total==0){
            $this->buildSaleSpecIs = false;
            $this->assignconfig('buildSaleSpecIs', $this->buildSaleSpecIs);
        }

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->count();

            $list = collection($this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select())->toArray();

            //如果未生成销售表，则生成
            foreach ($list as &$row) {
                //获取销售规格
                $specItems = $row["specitem_ids"];
                $specItems = explode(":",$specItems);
                foreach ($specItems as $item) {
                    //循环查找规格项
                    foreach ($this->Items as $val) {
                        //匹配到规格项
                        if($item == $val['itemId']){
                            //$val["spec_id"]  匹配到的规格ID
                            //给$list增加分类规格列,列名为"specid_".$val["spec_id"]
                            $row["specid_" . $val['spec_id']] = $val['itemname'];
                        }
                    }
                }
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        //读取商品相关数量作为销售规格默认值
        $goods = db('mall_goods_goods')
            ->where("id",$this->goods_id)
            ->field("productno,marketprice,shopprice,goodsstock,warnstock")
            ->find();
        $i = 0;
        //获取已设置的分类规格ID
        $specids = array_column($this->Items,"spec_id");
        $specids = array_unique($specids);

        $siArr=[];
        foreach ($specids as $specid) {
            //获取已设置的单个分类规格的设置项,并将项ID转换成KV数组
            //$specItem = $this->Items->where("spec_id", $specid);
            $temp = [];
            foreach ($this->Items as $item) {
                if ($item["spec_id"] == $specid) {
                    $temp[] = $item["itemId"];
                }
            }
            //foreach ($specItem as $siVal) {
            //$temp[] = $siVal["itemId"];
            //}
            $siArr[] = $temp;
        }
        //获取规格项矩阵
        $arrSpect = $this->combined($siArr);
        //生成销售规格列表
        $list = [];
        foreach ($arrSpect as $val) {
            $i++;
            $row = [];
            $row["goods_id"] = $this->goods_id;
            if(is_array($val)) sort($val);
            $row["specitem_ids"] = is_array($val) ? implode(":", $val) : $val;
            $row["productno"] = $goods['productno']."-". $i;
            $row["marketprice"] = $goods['marketprice'];
            $row["specprice"] = $goods['shopprice'];
            $row["specstock"] = $goods['goodsstock'];
            $row["warnstock"] = $goods['warnstock'];
            $list[] = $row;
        }
        $list[0]["defaultis"] = 1;

        try {
            //如果已生成过销售规格表，则删除原有数据
            if($this->buildSaleSpecIs) $this->model->where("goods_id",$this->goods_id)->delete();
            $result = $this->model->allowField(true)->saveAll($list);
            if ($result !== false) {
                //更新商品specis字段值，表明有规格，以便前端展示
                db("mall_goods_goods")->where("id",$this->goods_id)->update(["specis"=>1]);
                $this->success();
            } else {
                $this->error($this->model->getError());
            }
        } catch (\think\exception\PDOException $e) {
            $this->error($e->getMessage());
        } catch (\think\Exception $e) {
            $this->error($e->getMessage());
        }

    }

    /**
     * 批量更新
     */
    public function multi($ids = "")
    {
        $ids = $ids ? $ids : $this->request->param("ids");
        if ($ids)
        {
            if ($this->request->has('params'))
            {
                $values = [];
                parse_str($this->request->post("params"), $values);
                $values = array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
                if ($values)
                {
                    $admin_ids = $this->getDataLimitAdminIds();
                    if (is_array($admin_ids))
                    {
                        $this->model->where($this->dataLimitField, 'in', $admin_ids);
                    }
                    $count=0;
                    //$count =$this->model->where($this->model->getPk(), 'in', $ids)->update($values);//更新当前记录为默认值成功
                    $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
                    foreach ($list as $item) {
                        $count += $item->allowField(true)->isUpdate(true)->save($values);
                    }
                    if ($count)
                    {
                        if($values['defaultis']){
                            //更新其它记录为非默认值
                            $this->model->where( [ ["id",'<>',$ids],['goods_id','=',$this->goods_id] ] )->setField('defaultis',0);
                        }
                        $this->success();
                    }
                    else
                    {
                        $this->error(__('No rows were updated'));
                    }
                }
                else
                {
                    $this->error(__('You have no permission'));
                }
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    /*
     * 生成规格项矩阵
     * @param string $doubleArrays 已设置的规格项数组
     */
    private function combined($doubleArrays){
        $len = count($doubleArrays);
        if ($len >= 2) {//二组的，生成矩阵
            $arr1 = $doubleArrays[0];//取出第一组规格项
            $arr2 = $doubleArrays[1];//取出第二组规格项
            $temp = $ntemp = [];
            $index = 0;
            foreach ($arr1 as $v1) {
                //v1第一次是一个规格名，递归后是上一次的规格项ID数组（计数大于1）
                if(count($v1)>1){
                    foreach($arr2 as $v2) {
                        $ntemp = $v1;
                        array_push($ntemp, $v2);//组装成规格项大于2的数组
                        $temp[$index] = $ntemp;
                        $index++;
                    }
                }else{
                    foreach($arr2 as $v2) {
                        $temp[$index] = [$v1,$v2];//组装成新数组
                        $index++;
                    }
                }
            }
            $newArray = [];
            $newArray[0] = $temp;//保存结果，作为递归的第一组规格项
            if ($len > 2) {//二组以上的，递归生成矩阵
                $_count = 1;
                //去掉前面两组规格项，生成新的规格项数组进行递归
                for ($i = 2; $i < $len; $i++) {
                    $newArray[$_count] = $doubleArrays[$i];
                    $_count++;
                }
            }
            return $this->combined($newArray);
        }else {
            return $doubleArrays[0];//仅有一组的，无需生成矩阵
        }
    }
}
